/**
 * SSE管理器 - 负责处理消息路由和分发
 * 不包含具体业务逻辑，仅负责连接管理和事件分发
 */
const SSEManager = {
    connection: null,
    initialized: false,
    signatureRefreshTimeout: null,
    
    // 注册表 - 存储所有事件处理函数引用
    eventHandlers: {
        beforeunload: null,
        userDataUpdated: null,
        userDataCleared: null,
        sseStateChange: null
    },
    
    /**
     * 初始化SSEManager
     */
    init() {
        if (this.initialized) return Promise.resolve(this.connection);
        
        // 设置事件处理器
        this._setupEventHandlers();
        
        this.initialized = true;
        console.log('SSEManager初始化完成');
        
        // 尝试初始化连接
        return this.initConnection();
    },
    
    /**
     * 设置所有事件处理器
     */
    _setupEventHandlers() {
        // 保存处理函数引用
        this.eventHandlers.beforeunload = () => this._handleBeforeUnload();
        this.eventHandlers.userDataUpdated = () => this._handleUserDataUpdated();
        this.eventHandlers.userDataCleared = () => this._handleUserDataCleared();
        this.eventHandlers.sseStateChange = (event) => this._handleStateChange(event);
        
        // 注册全局事件监听
        window.addEventListener('beforeunload', this.eventHandlers.beforeunload);
        document.addEventListener('userDataUpdated', this.eventHandlers.userDataUpdated);
        document.addEventListener('userDataCleared', this.eventHandlers.userDataCleared);
        document.addEventListener('sse-state-change', this.eventHandlers.sseStateChange);
        
        // 通用SSE消息处理器 - 负责将SSE事件转换为业务事件并分发
        this._messageEventHandler = event => {
            try {
                const data = JSON.parse(event.data);
                const eventType = data.type || 'unknown';
                
                console.log(`SSE收到消息，类型: ${eventType}`, data);
                
                // 分发业务事件 - 使用统一的事件命名格式
                const businessEvent = new CustomEvent(`sse-business-${eventType}`, {
                    detail: data
                });
                document.dispatchEvent(businessEvent);
                
                // 同时触发通用业务消息事件，便于全局监听
                const genericEvent = new CustomEvent('sse-business-message', {
                    detail: { type: eventType, data: data }
                });
                document.dispatchEvent(genericEvent);
            } catch (err) {
                console.error('处理SSE消息时出错:', err);
            }
        };
    },
    
    /**
     * 获取SSE签名
     * @param {string} userId - 用户ID
     */
    async getSignature(userId) {
        try {
            const response = await fetch(`${SSE_CONFIG.SIGNATURE_ENDPOINT}?user_id=${userId}`);
            if (!response.ok) {
                throw new Error(`获取签名失败: ${response.status} ${response.statusText}`);
            }
            return await response.json();
        } catch (err) {
            console.error('获取SSE签名失败:', err);
            throw err;
        }
    },
    
    /**
     * 初始化SSE连接
     */
    async initConnection() {
        // 关闭现有连接
        this.closeConnection();

        // 获取用户数据
        const userData = await UserDataCache.getUserData();
        if (!userData?.data?.user_id) {
            console.log('未找到用户ID，不创建SSE连接');
            return null;
        }

        const userId = userData.data.user_id;
        console.log(`初始化SSE连接，用户ID: ${userId}`);
        
        try {
            // 获取签名
            const signatureData = await this.getSignature(userId);
            console.log('成功获取SSE连接签名');
            
            // 直接使用简化的通道名称，与后端一致
            const channel = `user.${userId}`;
            
            // 但还是传递签名用于验证
            const sseUrl = `${SSE_CONFIG.ENDPOINT}?channel=${channel}&user_id=${userId}&timestamp=${signatureData.timestamp}&signature=${signatureData.signature}`;
            
            // 创建增强型SSE连接
            this.connection = new EnhancedSSE(sseUrl, {
                maxRetries: SSE_CONFIG.MAX_RETRIES,
                retryDelay: SSE_CONFIG.RETRY_DELAY,
                onOpen: () => {
                    console.log(`用户${userId}的SSE连接已打开`);
                    document.dispatchEvent(new CustomEvent('sse-connected'));
                },
                onError: (error) => {
                    console.error('SSE错误:', error);
                    document.dispatchEvent(new CustomEvent('sse-error', { detail: error }));
                },
                onMaxRetries: () => {
                    console.log('SSE连接重试次数已达上限');
                    document.dispatchEvent(new CustomEvent('sse-max-retries'));
                    
                    // 签名可能过期，尝试重新获取签名
                    setTimeout(() => {
                        console.log('尝试重新获取签名并连接');
                        this.initConnection();
                    }, 3000);
                }
            });

            // 为所有事件类型添加通用处理器
            this.connection.eventSource.onmessage = this._messageEventHandler;
            
            // 添加特定事件监听 - 支持各种业务事件类型，无需关心具体业务逻辑
            ['notification', 'profile_updated', 'system_config', 'site_data_updated'].forEach(eventName => {
                this.connection.addEventListener(eventName, this._messageEventHandler);
            });

            // 设置签名过期前的自动刷新
            if (signatureData.expires_in) {
                const refreshTimeout = (signatureData.expires_in - 30) * 1000; // 提前30秒刷新
                this.signatureRefreshTimeout = setTimeout(() => {
                    console.log('签名即将过期，刷新连接');
                    this.initConnection();
                }, refreshTimeout);
            }

            return this.connection;
        } catch (err) {
            console.error('创建SSE连接失败:', err);
            // 延迟重试
            setTimeout(() => this.retryConnection(), 5000);
            return null;
        }
    },
    
    /**
     * 重试建立连接
     */
    retryConnection() {
        if (!this.connection) {
            console.log('尝试重新建立SSE连接');
            return this.initConnection();
        }
        return Promise.resolve(this.connection);
    },
    
    /**
     * 关闭SSE连接
     */
    closeConnection() {
        // 清除签名刷新计时器
        if (this.signatureRefreshTimeout) {
            clearTimeout(this.signatureRefreshTimeout);
            this.signatureRefreshTimeout = null;
        }

        if (this.connection) {
            // 确保关闭连接前移除事件处理器
            if (this._messageEventHandler) {
                if (this.connection.eventSource) {
                    this.connection.eventSource.onmessage = null;
                }
                
                ['notification', 'profile_updated', 'system_config', 'site_data_updated'].forEach(eventName => {
                    this.connection.removeEventListener(eventName, this._messageEventHandler);
                });
            }
            
            this.connection.close();
            this.connection = null;
        }
    },
    
    /**
     * 销毁SSEManager
     */
    destroy() {
        try {
            // 移除所有事件监听
            window.removeEventListener('beforeunload', this.eventHandlers.beforeunload);
            document.removeEventListener('userDataUpdated', this.eventHandlers.userDataUpdated);
            document.removeEventListener('userDataCleared', this.eventHandlers.userDataCleared);
            document.removeEventListener('sse-state-change', this.eventHandlers.sseStateChange);
            
            // 清除资源
            this.closeConnection();
            this.eventHandlers = {};
            this.initialized = false;
            
            console.log('SSEManager已完全销毁');
        } catch (err) {
            console.error('销毁SSEManager时出错:', err);
            this.initialized = false;
        }
    },
    
    /**
     * 处理页面卸载事件
     */
    _handleBeforeUnload() {
        this.closeConnection();
    },
    
    /**
     * 处理用户数据更新事件
     */
    _handleUserDataUpdated() {
        UserDataCache.isUserLoggedIn().then(isLoggedIn => {
            if (isLoggedIn) {
                this.initConnection();
            }
        });
    },
    
    /**
     * 处理用户数据清除事件
     */
    _handleUserDataCleared() {
        this.closeConnection();
    },
    
    /**
     * 处理连接状态变化 - 仅记录日志，不包含业务逻辑
     */
    _handleStateChange(event) {
        const { state } = event.detail;
        console.log(`SSE连接状态变更: ${state}`);
    }
};

// 导出到全局
window.SSEManager = SSEManager;